document.addEventListener('DOMContentLoaded', function() {
    // 检查是否有记住的登录信息
    const rememberedUser = localStorage.getItem('rememberedUser');
    if (rememberedUser) {
        const user = JSON.parse(rememberedUser);
        document.getElementById('username').value = user.username;
        document.getElementById('password').value = user.password;
        document.getElementById('remember').checked = true;
    }

    document.getElementById('loginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();
        const remember = document.getElementById('remember').checked;
        let isValid = true;
        
        // 验证用户名
        if (username === '') {
            document.getElementById('usernameError').textContent = '请输入用户名';
            isValid = false;
        } else if (username.length < 4) {
            document.getElementById('usernameError').textContent = '用户名至少4个字符';
            isValid = false;
        } else {
            document.getElementById('usernameError').textContent = '';
        }
        
        // 验证密码
        if (password === '') {
            document.getElementById('passwordError').textContent = '请输入密码';
            isValid = false;
        } else if (password.length < 6) {
            document.getElementById('passwordError').textContent = '密码至少6个字符';
            isValid = false;
        } else {
            document.getElementById('passwordError').textContent = '';
        }
        
        if (isValid) {
            // 模拟AJAX登录
            const users = JSON.parse(localStorage.getItem('users')) || [];
            const user = users.find(u => u.username === username && u.password === password);
            
            if (user) {
                // 登录成功，保存用户信息
                localStorage.setItem('currentUser', JSON.stringify(user));
                
                // 记住我功能
                if (remember) {
                    localStorage.setItem('rememberedUser', JSON.stringify({ username, password }));
                } else {
                    localStorage.removeItem('rememberedUser');
                }
                
                // 显示登录成功提示
                alert('登录成功！');
                
                // 跳转到首页或之前的页面
                const returnUrl = new URLSearchParams(window.location.search).get('returnUrl');
                window.location.href = returnUrl || 'index.html';
            } else {
                alert('用户名或密码错误！');
            }
        }
    });
});